// 导入样式
import 'tea-component/lib/tea.css';
import '../ide/app.less';
import chainmakerLOGO from '@/assets/svgs/chainmakerLOGO.svg';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { accountWs, audit, getConfig, logOut, updateSessionDebounce } from '@/api';
import { getSid, setSid } from '@/api/request';
import { Badge, Bubble, Button, Icon, Select, message } from 'tea-component';
import { currentVersion, versionMap } from '@/config';
import { GetRequest, getContractNameByPath } from '@ide/utils/tools';
import { IdeComponent, useIdeStore } from 'ide-plugin';
import useAppStore from '@ide/store';
import SideMenu from '@ide/components/SideMenu';
import SideTab from '@ide/components/sideTab';
import Structure from '@ide/components/structure';
import BottomConsole from '@ide/components/bottomConsole';
import { ideEventListenerCreater } from '@ide/ideEventListener';
import 'ide-plugin/style.css';
import AlertModal from '@ide/components/alertModal';
import AddFileModel from '@ide/components/fileModel';
import ManageComplieContract from '@ide/components/models/manageComplieContract';
import ManageDeployContract from '@ide/components/models/manageDeployContract';
import ManageHiddenContract from '@ide/components/models/manageHiddenContract';
import NewContractByTemplate from '@ide/components/models/newContractByTemplate';
import SetModal from '@ide/components/set/set';
// import { useAppOpenEditor } from '@/hooks/useAppOpenEditor';

export default function IdePage() {
  const [pageActionReady, setPageActionReady] = useState<boolean>(false);
  const [hasInitEditByConfig, setHasInitEditByConfig] = useState<boolean>(false);
  const [config, setConfig] = useState<any>();
  const ideStore = useIdeStore();
  const appStore = useAppStore();
  const {
    openEditor, setEditors, ideFileTabs, currentFileTab, leftContentSize, rightContentSize, bottomContentSize,
    setLeftContentSize, setBottomContentSize, setRightContentSize, isHideBottomContent, isHideLeftContent, isHideRightContent,
    setIsHideBottomContent, setIsHideLeftContent, setIsHideRightContent, updateEditor,saveAll
  } = ideStore;
  // const { appOpenEditor } = useAppOpenEditor();
  const {
    chainmakerVersion, setChainmakerVersion, setUserId, fileTree, setIdeSetting, setIsPluginReady,
    leftCurrentTab, expandedIds, setLeftCurrentTab, setExpandedIds
  } = appStore;

  useEffect(() => {
    setChainmakerVersion(currentVersion);

    getConfig({}).then(res => {
      setConfig(res);
      const user = res.user;
      setIdeSetting({
        editorFontSize: user.Editor.fontSize,
        editorLineHeight: user.Editor.lineHeight,
        editorTheme: user.Editor.theme,
        theme: res.Theme || 'dark'
      });
      setUserId(user.ID);
      setSid(res.sid);
      if (res.latestSessionContent?.fileTree?.length) {
        setExpandedIds(res.latestSessionContent.fileTree);
      }
      if (res.latestSessionContent?.layout?.side?.state) {
        setLeftCurrentTab(res.latestSessionContent.layout.side.state);
      }
      if (res.latestSessionContent?.sideRight?.size) {
        setRightContentSize(res.latestSessionContent.sideRight.size);
      }
      if (res.latestSessionContent?.layout?.side?.size) {
        setLeftContentSize(res.latestSessionContent.layout.side.size);
      }
      if (res.latestSessionContent?.layout?.bottom?.size) {
        setBottomContentSize(res.latestSessionContent.layout.bottom.size);
      }
      setPageActionReady(true);
    });
  }, []);

  const switchVersion = (version:string) => {
    console.log(version);
    if (version !== chainmakerVersion) {
      window.location.href = `${(versionMap as any)[version].serverHost}login/redirect?auth_server=CHAINMAKER&site=${encodeURIComponent((versionMap as any)[version].pageHost)}`;
    }
  };

  useEffect(() => {
    if (!pageActionReady) {
      return;
    }
    setTimeout(() => {
      const account = accountWs({});
      account.addEventListener('message', (e:any) => {
        console.log(e);
      });
    }, 100);
    // account.addEventListener('error', (error:any) => {
    //   message.error({
    //     content: error.toString()
    //   });
    // });
    // account.addEventListener('close', () => {
    //   message.warning({
    //     content: 'socket会话已关闭'
    //   });
    // });
  }, [pageActionReady]);

  useEffect(() => {
    if (!hasInitEditByConfig) {
      return;
    }
    updateSessionDebounce({
      currentFile: currentFileTab?.path,
      fileTree: expandedIds,
      files: ideFileTabs.map(editor => editor.path),
      layout: {
        side: {
          size: leftContentSize,
          state: leftCurrentTab
        },
        sideRight: {
          size: rightContentSize,
          state: ''
        },
        bottom: {
          size: bottomContentSize
        }
      }
    });
  }, [ideFileTabs, currentFileTab, leftCurrentTab, expandedIds, leftContentSize, rightContentSize, bottomContentSize]);

  useEffect(() => {
    console.log('init by config');
    if (hasInitEditByConfig) {
      return;
    }
    if (fileTree?.length && config?.latestSessionContent) {
      if (config.latestSessionContent.files?.length) {
        setEditors([]);
        const l = config.latestSessionContent.files.length;
        for(var i = l-1;i>=0;i--){
          openEditor({
            path: config.latestSessionContent.files[i]
          });
        }
      }
      if (config.latestSessionContent.currentFile) {
        openEditor({
          path: config.latestSessionContent.currentFile
        });
      }
      setTimeout(() => {
        setHasInitEditByConfig(true);
      }, 2000);
    }
  }, [hasInitEditByConfig, fileTree, config]);

  const ideEventListener = useMemo(() => {
    return ideEventListenerCreater(ideStore, appStore);
  }, [ideStore, appStore]);

  const logout = useCallback(() => {
    logOut({}).then(() => {
      location.href = '/login';
    });
  }, []);

  useEffect(() => {
    if (pageActionReady) {
      const urlParam = GetRequest();
      if (urlParam?.leftNav && urlParam.leftNav !== '') {
        // setActiveTab('contractCall')
        setLeftCurrentTab(urlParam.leftNav);
        // editor.current?.switchLeftNav(urlParam.leftNav);
      }
    }
  }, [pageActionReady]);
  useEffect(() => {
    setTimeout(() => {
      if ((window as any).chainMaker) {
        setIsPluginReady(true);
      }
    }, 1000);
  }, []);
  useEffect(() => {
    // 更新页面关闭拦截函数，在存在未保存的文件是拦截关闭
    window.onbeforeunload = function () {
      const hasUnSaveEditor = ideFileTabs.find((item) => item.hasUnSave);
      if (hasUnSaveEditor) {
        return 'there are unsaved file';
      }
    };
  }, [ideFileTabs]);
  const isFull = useMemo(() => {
    return isHideBottomContent && isHideLeftContent && isHideRightContent;
  }, [isHideBottomContent, isHideLeftContent, isHideRightContent]);
  const switchFull = useCallback(() => {
    setIsHideBottomContent(!isFull);
    setIsHideLeftContent(!isFull);
    setIsHideRightContent(!isFull);
  }, [isFull]);
  const auditAction = useCallback(() => {
    const contractName = getContractNameByPath(currentFileTab?.path);
    if (!contractName) {
      message.error({
        content: '请打开要审查的合约'
      });
      return;
    }
    audit({
      sid: getSid(),
      contractName
    });
  }, [currentFileTab]);
  return <>
    {pageActionReady && <IdeComponent
      headerContent={
        <div className="chainmaker_header_ide">
          <div className="chainmaker_header_icon">
            <img src={chainmakerLOGO} />
            <span>ChainMaker SmartEditor</span>
          </div>
          <div className="chainmaker_header_flex"></div>
          <div className='chainmaker_header_version'>
          长安链版本：
            <Select
              appearance="default"
              options={[{
                value: 'v2.1.0+'
              }, {
                value: 'v2.3.0+'
              }]}
              value={chainmakerVersion}
              onChange={switchVersion}
            />
            <Bubble
              arrowPointAtCenter
              placement="bottom"
              content="请选择你要编写的合约最终要被部署的长安链的版本，根据版本不同，所能引用到的合约SDK将不同，编译出来的合约内容也会有差异。"
            >
              <Icon type="help" /></Bubble>
          </div>
          <div className="chainmaker_header_user">
            {config?.user?.Name}
          </div>
          <div onClick={logout} className="chainmaker_header_link">退出</div>
        </div>
      }

      leftNavMenuContent={
        <SideMenu
          value={leftCurrentTab}
          onChange={(type) => {
            setLeftCurrentTab(type);
          }}
        ></SideMenu>
      }
      leftContent={
        <SideTab />
      }
      rightContent={
        <Structure />
      }
      bottomContent={
        <BottomConsole />
      }
      codeOptionContent={
        <div className='code_op_ls'>
          <Button onClick={auditAction} type="primary">审查<Badge theme="warning" dark>新</Badge></Button>
          <Button onClick={saveAll} type="primary">保存</Button>
          <Button onClick={switchFull} type="primary">{isFull ? '收起' : '全屏'}</Button>
        </div>
      }
      ideEventListener={ideEventListener} ></IdeComponent>
    }
    <AddFileModel />
    <AlertModal />
    <SetModal />
    <NewContractByTemplate/>
    <ManageDeployContract/>
    <ManageComplieContract/>
    <ManageHiddenContract/>
  </>;
}
